package com.demo.steammanagement.controller;


import cn.hutool.core.util.ObjectUtil;
import com.demo.steammanagement.common.RedisConstants;
import com.demo.steammanagement.model.dto.UserDto;
import com.demo.steammanagement.model.entity.Users;
import com.demo.steammanagement.model.vo.Result;
import com.demo.steammanagement.model.vo.UserVO;
import com.demo.steammanagement.service.CaptchaService;
import com.demo.steammanagement.service.IUsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import javax.validation.Valid;

@RestController
@RequestMapping("register")
@Validated
public class RegisterController {

  @Autowired
  private IUsersService usersService;
  @Autowired
  private CaptchaService captchaService;

  @PostMapping
  public Result register(@Valid @RequestBody UserDto vo ) {
    boolean b = usersService.existsByUsername(vo.getAccount());
    // 检查用户名是否存在
    if (b) {
      return Result.fail(400, "用户名已存在");
    }
    boolean existsByEmail = usersService.existsByEmail(vo.getEmail());
    if(existsByEmail){
      return Result.fail(400, "email已被绑定");
    }
    boolean isValid = captchaService.validateCaptcha(RedisConstants.REGISTER_CAPTCHA_KEY_PREFIX, vo.getEmail(), vo.getCaptcha());
    if(!isValid){
      // 如果失败，可以跳转到错误页面或返回错误提示
      return Result.fail(400, "验证码失效或错误");
    }
    boolean isRegistered = usersService.registerUser(vo);
    if (isRegistered) {
      // 注册成功后重定向到登录页面
      return Result.success( "注册成功");
    } else {
      return Result.fail(400, "注册失败");
    }

  }
  // 忘记密码 找回密码
  @PostMapping("/retrieve")
  public Result retrieve(@RequestBody UserVO vo) throws Exception {
    if(ObjectUtil.isEmpty(vo.getEmail())||ObjectUtil.isEmpty(vo.getAccount())||ObjectUtil.isEmpty(vo.getCaptcha())){
      return Result.fail(400, "信息不能为null");
    }
    Users user = usersService.getUserByEmailAndAccount(vo.getEmail(),vo.getAccount());
    if(ObjectUtil.isEmpty(user)){
      return Result.fail(400, "信息不存在，请检查你的用户或者邮箱");
    }
    boolean isValid = captchaService.validateCaptcha(RedisConstants.FIND_PWD_CAPTCHA_KEY_PREFIX, vo.getEmail(), vo.getCaptcha());
    if(!isValid){
      // 如果失败，可以跳转到错误页面或返回错误提示
      return Result.fail(400, "验证码失效或错误");
    }
    // 修改密码
    usersService.retrievePassword(vo);
    return Result.success("找回成功");
  }
}
